/***********************************************************************************
  * File:			led.c
  * Version:		V1.0
  * Date:			2021.5.26
  * Description:	LED应用函数接口
***********************************************************************************/

/* 头文件 */
#include <rtthread.h>
#include <n32g45x.h>
#include "led.h"

/**
 * @brief  Configures LED GPIO.
 * @param GPIOx x can be A to G to select the GPIO port.
 * @param Pin This parameter can be GPIO_PIN_0~GPIO_PIN_15.
 */
void LedInit(GPIO_Module* GPIOx, uint16_t Pin)
{
    GPIO_InitType GPIO_InitStructure;

    /* Check the parameters */
    assert_param(IS_GPIO_ALL_PERIPH(GPIOx));

    /* Enable the GPIO Clock */
    if (GPIOx == GPIOA)
    {
        RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_GPIOA, ENABLE);
    }
    else if (GPIOx == GPIOB)
    {
        RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_GPIOB, ENABLE);
        GPIO_ConfigPinRemap(GPIO_RMP_SW_JTAG_SW_ENABLE,ENABLE);  //PB4默认为JTAG复用
    }
    else if (GPIOx == GPIOC)
    {
        RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_GPIOC, ENABLE);
    }
    else if (GPIOx == GPIOD)
    {
        RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_GPIOD, ENABLE);
    }
    else if (GPIOx == GPIOE)
    {
        RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_GPIOE, ENABLE);
    }
    else if (GPIOx == GPIOF)
    {
        RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_GPIOF, ENABLE);
    }
    else
    {
        if (GPIOx == GPIOG)
        {
            RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_GPIOG, ENABLE);
        }
    }

    /* Configure the GPIO pin */
    if (Pin <= GPIO_PIN_ALL)
    {
        GPIO_InitStructure.Pin        = Pin;
        GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_Out_PP;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
        GPIO_InitPeripheral(GPIOx, &GPIO_InitStructure);
    }
    GPIO_ResetBits(GPIOx, Pin);
}
/**
 * @brief  led init
 */
void rt_hw_led_init(void)
{
    LedInit(LED1_PORT, LED1_PIN);
    LedInit(LED2_PORT, LED2_PIN);
    LedInit(LED3_PORT, LED3_PIN);
}
/**
 * @brief  open led
 * @param  n: led num
 */
void rt_hw_led_on(rt_uint32_t n)
{
    switch (n)
    {
    case 0:
        GPIO_SetBits(LED1_PORT, LED1_PIN);
        break;
    case 1:
        GPIO_SetBits(LED2_PORT, LED2_PIN);
        break;
    case 2:
        GPIO_SetBits(LED3_PORT, LED3_PIN);
    default:
        break;
    }
}
/**
 * @brief  close led
 * @param  n: led num
 */
void rt_hw_led_off(rt_uint32_t n)
{
    switch (n)
    {
    case 0:
        GPIO_ResetBits(LED1_PORT, LED1_PIN);
        break;
    case 1:
        GPIO_ResetBits(LED2_PORT, LED2_PIN);
        break;
    case 2:
        GPIO_ResetBits(LED3_PORT, LED3_PIN);
    default:
        break;
    }
}

void led_run(int led_id, int time)
{
    rt_hw_led_on(led_id);
    rt_thread_delay(time);
    rt_hw_led_off(led_id);
    rt_thread_delay(time);
}
